package com.control.qct.businesssteward.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.adapter.GoodsTypeAdapter;
import com.control.qct.businesssteward.adapter.GoodsTypeDetailAdapter;
import com.control.qct.businesssteward.base.BaseActivity;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.GoodsChildTypeModel;
import com.control.qct.businesssteward.model.GoodsParentTypeModel;
import com.control.qct.businesssteward.utils.EditTextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 品类选择
 * Created by Administrator on 2017/12/16 0016.
 */

public class GoodsTypeActivity extends BaseActivity implements GoodsTypeDetailAdapter.IGetGoodsTypeName {
    @BindView(R.id.rv_goods_type)
    RecyclerView mRvGoodsType;
    @BindView(R.id.rv_goods_type_detail)
    RecyclerView mRvGoodsTypeDetail;
    @BindView(R.id.tv_already_select_type)
    TextView mTvAlreadySelectType;
    @BindView(R.id.ll_already_select_type)
    LinearLayout mLlAlreadySelectType;
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;

    private GoodsTypeAdapter mGoodsTypeAdapter;
    private List<GoodsParentTypeModel> mGoodsParentTypeModelList;
    private List<GoodsChildTypeModel> mGoodsChildTypeModelList = new ArrayList<>();
    ;
    private GoodsTypeDetailAdapter mGoodsTypeDetailAdapter;
    //多选  --  选中的品类 --  品类对应的id
    private StringBuilder sbGoodsTypeName = new StringBuilder();
    private StringBuilder sbGoodsTypeNameSN = new StringBuilder();
    private List<String> mCategoryList = new ArrayList<>();
    private List<String> mCategorySNList = new ArrayList<>();
    private Map<Integer, Object> data = new HashMap<>();

    private int id;//区分为多选还是单选 1为多选
    private String parentType = "";//一级类别
    private int mCategorySN;//单选状态下选择的品类对应id
    private String mSelectType[];//已选择的品类数组//多选状态下--已选品类对应的id
    private String mSelectTypeName;//多选状态下--已选品类
    private String[] mSelectTypeNameArray;//多选状态下--已选品类数组
    private String[] mSelectTypeNameArraySN;//多选状态下--已选品类对应的id数组

    public GoodsTypeActivity() {
        super(R.layout.activity_goods_type);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        id = extras.getInt("id");
        mSelectType = extras.getString("value").split("/");
        mSelectTypeName = extras.getString("type", "");
        mCategorySN = extras.getInt("categorySN");
    }

    @Override
    protected void initView() {
        setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitle("商品");
        if (id == 1) {
            setRightIcon("完成", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("type", sbGoodsTypeName.toString());
                    intent.putExtra("typeSN", sbGoodsTypeNameSN.toString());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
            mLlAlreadySelectType.setVisibility(View.VISIBLE);
            mTvAlreadySelectType.setText(mSelectTypeName);
            sbGoodsTypeName.append(mSelectTypeName);
            sbGoodsTypeNameSN.append(mSelectType[0]);
            //拆解字符串 获取单独的品类名称及对应的id
            mSelectTypeNameArray = mSelectTypeName.split(",");
            mSelectTypeNameArraySN = mSelectType[0].split(",");
            if (!TextUtils.isEmpty(mSelectTypeNameArray[0])) {//如果不为空 则已有选择品类  才往下执行
                for (int i = 0; i < mSelectTypeNameArray.length; i++) { //将已选择的品类添加到集合中
                    mCategoryList.add(mSelectTypeNameArray[i]);
                    mCategorySNList.add(mSelectTypeNameArraySN[i]);
                }
            }
        }
        //判断是否有选择品类 有则显示删除按钮
        mIvDelete.setVisibility(TextUtils.isEmpty(mTvAlreadySelectType.getText().toString()) ? View.GONE : View
                .VISIBLE);
        getGoodsParentType();
        mRvGoodsType.setLayoutManager(new LinearLayoutManager(this));
        mGoodsTypeAdapter = new GoodsTypeAdapter(mGoodsParentTypeModelList);
        mRvGoodsType.setAdapter(mGoodsTypeAdapter);
        mGoodsTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mGoodsTypeAdapter.setPosition(position);
                parentType = ((List<GoodsParentTypeModel>) adapter.getData()).get(position).getTitle();
                if (mGoodsTypeDetailAdapter != null) {
                    List<GoodsChildTypeModel> goodsChildTypeModels = (List<GoodsChildTypeModel>) data.get((
                            (List<GoodsParentTypeModel>) adapter.getData()).get(position).getCategorySN());
                    //判断是否已经联网获取过值  有值则直接显示  不在联网获取 保存状态
                    if (goodsChildTypeModels != null) {
                        mGoodsChildTypeModelList.clear();
                        mGoodsChildTypeModelList.addAll(goodsChildTypeModels);
                        mGoodsTypeDetailAdapter.notifyDataSetChanged();
                        return;
                    }
                }
                getGoodsChildTypeModel(((List<GoodsParentTypeModel>) adapter.getData()).get(position).getCategorySN());

            }
        });

        if (mSelectType.length < 2) {//判断是否有选择品类  没有则请求全部商品 有则请求该品类下的数据
            getGoodsChildTypeModel(1);
        }
        mRvGoodsTypeDetail.setLayoutManager(new LinearLayoutManager(this));
        mGoodsTypeDetailAdapter = new GoodsTypeDetailAdapter(mGoodsChildTypeModelList, this);
        mRvGoodsTypeDetail.setAdapter(mGoodsTypeDetailAdapter);
        EditTextUtils.isEditContent(mTvAlreadySelectType, mIvDelete);
    }

    /**
     * 获取商品主类别
     */
    private void getGoodsParentType() {
        mGoodsParentTypeModelList = new ArrayList<>();
        mNetProtocol.getGoodsParentType(this, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                List<GoodsParentTypeModel> goodsParentTypeModels = (List<GoodsParentTypeModel>) baseBean.getData();
                parentType = goodsParentTypeModels.get(0).getTitle();
                mGoodsParentTypeModelList.addAll(goodsParentTypeModels);
                if (mGoodsTypeAdapter != null) {
                    for (int i = 0; i < mGoodsParentTypeModelList.size(); i++) {//循环判断是否已选中
                        if (mSelectType != null && mGoodsParentTypeModelList.get(i).getTitle().equals(mSelectType[0])) {
                            mGoodsTypeAdapter.setPosition(i);
                            parentType = mGoodsParentTypeModelList.get(i).getTitle();
                            getGoodsChildTypeModel(mGoodsParentTypeModelList.get(i).getCategorySN());
                        }
                    }
                    mGoodsTypeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }


    /**
     * 获取商品子类别
     *
     * @param position
     */
    private void getGoodsChildTypeModel(final int position) {
        mNetProtocol.getGoodsChildType(this, position, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                mGoodsChildTypeModelList.clear();
                ArrayList<GoodsChildTypeModel> goodsChildTypeModels = (ArrayList<GoodsChildTypeModel>) baseBean
                        .getData();
                data.put(position, goodsChildTypeModels); //保存数据
                mGoodsChildTypeModelList.addAll(goodsChildTypeModels);
                if (mGoodsTypeDetailAdapter != null) {
                    mGoodsTypeDetailAdapter.notifyDataSetChanged();
                    if (id == 1) {//多选模式下---循环判断是否已选择该品类
                        if (mSelectTypeNameArraySN != null) {
                            for (int i = 0; i < mGoodsChildTypeModelList.size(); i++) {
                                if (mGoodsChildTypeModelList.get(i).getChildrens().size() == 0) {
                                    for (int j = 0; j < mSelectTypeNameArraySN.length; j++) {
                                        if (mGoodsChildTypeModelList.get(i).getCategorySN() ==
                                                Integer.parseInt(TextUtils.isEmpty(mSelectTypeNameArraySN[j]) ? "-1" :
                                                        mSelectTypeNameArraySN[j])) {
                                            mGoodsChildTypeModelList.get(i).setChecked(true);
                                        }
                                    }
                                }
                                for (int j = 0; j < mGoodsChildTypeModelList.get(i).getChildrens().size(); j++) {
                                    for (int k = 0; k < mSelectTypeNameArraySN.length; k++) {
                                        if (mGoodsChildTypeModelList.get(i).getChildrens().get(j).getCategorySN() ==
                                                Integer.parseInt(TextUtils.isEmpty(mSelectTypeNameArraySN[k]) ? "-1" :
                                                        mSelectTypeNameArraySN[k])) {
                                            mGoodsChildTypeModelList.get(i).getChildrens().get(j).setChecked(true);
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        for (int i = 0; i < mGoodsChildTypeModelList.size(); i++) {//循环判断二级类别是否选中
                            if (mGoodsChildTypeModelList.get(i).getChildrens().size() == 0) {
                                if (mGoodsChildTypeModelList.get(i).getCategorySN() == mCategorySN) {
                                    mGoodsChildTypeModelList.get(i).setChecked(true);
                                }
                            }
                            for (int j = 0; j < mGoodsChildTypeModelList.get(i).getChildrens().size(); j++) {
                                if (mSelectType.length > 1)
                                    if (mGoodsChildTypeModelList.get(i).getTitle().equals(mSelectType[1])) {
                                        if (mGoodsChildTypeModelList.get(i).getChildrens().get(j).getCategorySN() ==
                                                mCategorySN) {
                                            mGoodsChildTypeModelList.get(i).getChildrens().get(j).setChecked(true);
                                        }
                                    }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }

    @Override
    public void getGoodsTypeName(String title, int categorySN, String name, boolean isChecked) {
        if (id == 1) {//多选
            if (isChecked) {
                if (TextUtils.isEmpty(name)) {
                    mCategoryList.add(title);
                } else {
                    mCategoryList.add(name);
                }
                mCategorySNList.add(categorySN + "");
            } else {
                if (TextUtils.isEmpty(name)) {
                    mCategoryList.remove(title);
                } else {
                    mCategoryList.remove(name);
                }
                mCategorySNList.remove(categorySN + "");
            }
            sbGoodsTypeName.delete(0, sbGoodsTypeName.length());
            sbGoodsTypeNameSN.delete(0, sbGoodsTypeNameSN.length());
            for (int i = 0; i < mCategoryList.size(); i++) {
                sbGoodsTypeName.append(mCategoryList.get(i));
                sbGoodsTypeNameSN.append(mCategorySNList.get(i));
                if (i < mCategoryList.size() - 1) {
                    sbGoodsTypeName.append(",");
                    sbGoodsTypeNameSN.append(",");
                }
            }
            mTvAlreadySelectType.setText(sbGoodsTypeName.toString());
        } else {//单选
            Intent intent = new Intent();
            if (TextUtils.isEmpty(name)) {
                intent.putExtra("data", parentType + "/" + title);
            } else {
                intent.putExtra("data", parentType + "/" + title + "/" + name);
            }
//            intent.putExtra("data", parentType + "/" + title + "/" + name);
            intent.putExtra("categorySN", categorySN);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除缓存数据
        data.clear();
        data = null;
    }

    @OnClick(R.id.iv_delete)
    public void onViewClicked() {
        mSelectTypeNameArraySN = null;
        mCategoryList.clear();
        mCategorySNList.clear();
        data.clear();
        sbGoodsTypeName.delete(0, sbGoodsTypeName.length());
        sbGoodsTypeNameSN.delete(0, sbGoodsTypeNameSN.length());
        mTvAlreadySelectType.setText(sbGoodsTypeName.toString());
        for (int i = 0; i < mGoodsTypeDetailAdapter.getData().size(); i++) {
            mGoodsTypeDetailAdapter.getData().get(i).setChecked(false);
            for (int j = 0; j < mGoodsTypeDetailAdapter.getData().get(i).getChildrens().size(); j++) {
                mGoodsTypeDetailAdapter.getData().get(i).getChildrens().get(j).setChecked(false);
            }
        }
        mGoodsTypeDetailAdapter.notifyDataSetChanged();
    }
}
